# -*- coding: utf-8 -*-
from application import app, db
from flask import Blueprint, request, make_response, redirect
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON, ops_render, iPagenation
from common.libs.DataHelper import getCurrentTime
from common.libs.UrlManager import UrlManager
from common.models.user import User
from common.models.city import City
from common.models.appconfig import Appconfig
from common.models.department import Department
from common.models.weight import Weight
from common.libs.UserService import UserService
from common.libs.WXBizDataCrypt import WXBizDataCrypt
import json, requests

member_page = Blueprint("member_page", __name__)


@member_page.route('/changecity', methods=['GET', 'POST'])
def changecity():
    req = request.values
    uid = req['uid'] if "uid" in req else ""
    city = req['city'] if "city" in req else ""
    a = User.query.filter_by(id=uid).first()
    a.city = city
    db.session.commit()
    return ops_renderJSON(msg="城市变更成功")


@member_page.route('/getcity', methods=['GET', 'POST'])
def getcity():
    a = City.query.all()
    rts = []
    for item in a:
        temp = dict(city=item.city)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@member_page.route('/getcompany', methods=['GET', 'POST'])
def getCompany():
    a = Department.query.with_entities(Department.company).distinct().all()
    rts = []
    for item in a:
        temp = dict(company=item.company)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@member_page.route('/getcompany1', methods=['GET', 'POST'])
def getCompany1():
    req = request.values
    type = req['type'] if "type" in req else ""
    a = Department.query.filter_by(type=type).with_entities(Department.company).distinct().all()
    rts = []
    for item in a:
        temp = dict(company=item.company)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@member_page.route('/getdepartment', methods=['GET', 'POST'])
def getDepartment():
    req = request.values
    company = req['company'] if "company" in req else ""
    a = Department.query.filter_by(company=company).all()
    rts = []
    for item in a:
        temp = dict(department=item.department)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@member_page.route('/getdepartment1', methods=['GET', 'POST'])
def getDepartment1():
    req = request.values
    company = req['company'] if "company" in req else ""
    type = req['type'] if "type" in req else ""
    a = Department.query.filter_by(company=company, type=type).all()
    rts = []
    for item in a:
        temp = dict(department=item.department)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@member_page.route('/wxlogin1', methods=['GET', 'POST'])
def member_wxlogin1():
    data = json.loads(request.get_data().decode('utf-8'))  # 将前端Json数据转为字典
    code = data['platCode']  # 前端POST过来的微信临时登录凭证code
    type = data['type']
    appconfig = Appconfig.query.filter_by(company=type).first()
    appID = appconfig.appid
    appSecret = appconfig.appsecret

    encryptedData = data['platUserInfoMap']['encryptedData']
    iv = data['platUserInfoMap']['iv']
    req_params = {
        'appid': appID,
        'secret': appSecret,
        'js_code': code,
        'grant_type': 'authorization_code'
    }
    wx_login_api = 'https://api.weixin.qq.com/sns/jscode2session'
    response_data = requests.get(wx_login_api, params=req_params)  # 向API发起GET请求
    resData = response_data.json()
    openid = resData['openid']  # 得到用户关于当前小程序的OpenID
    session_key = resData['session_key']  # 得到用户关于当前小程序的会话密钥session_key

    pc = WXBizDataCrypt(appID, session_key)  # 对用户信息进行解密
    userinfo = pc.decrypt(encryptedData, iv)  # 获得用户信息

    user_info = User.query.filter_by(openid=openid).first()

    if not user_info:
        return json.dumps({"msg": "请注册", "res": "1", "openid": openid, "code": 400}, indent=4, sort_keys=True,
                          default=str,
                          ensure_ascii=False)

    if user_info.status != 1:
        return json.dumps({"msg": "锁定了"}, indent=4, sort_keys=True, default=str, ensure_ascii=False)

    name = user_info.nickname
    uid = user_info.id
    department = user_info.department
    company = user_info.company
    city = user_info.city
    status = user_info.status
    openid = user_info.openid
    role = user_info.role
    role = role.split(',')

    a = Weight.query.filter_by(city=city, type="用户应用").all()
    rtsu = []
    for item in a:
        temp = dict(name=item.name, image=item.image, fun=item.fun)
        rtsu.append(temp)
    rtsa = []
    for item1 in role:
        b = Weight.query.filter_by(role=item1, city=city, type="管理员应用").all()
        for item in b:
            temp = dict(name=item.name, image=item.image, fun=item.fun)
            rtsa.append(temp)

    return json.dumps(
        {"code": 200, "msg": "登录成功", "name": name, "uid": uid, "company": company, "department": department,
         "city": city, "status": status, "openid": openid, "weightu": rtsu, "weighta": rtsa},
        indent=4,
        sort_keys=True,
        default=str,
        ensure_ascii=False)


@member_page.route('/wxlogin', methods=['GET', 'POST'])
def member_wxlogin():
    data = json.loads(request.get_data().decode('utf-8'))  # 将前端Json数据转为字典
    code = data['platCode']  # 前端POST过来的微信临时登录凭证code
    appID = "wx15624353af4493ad"
    appSecret = "d7f09203305d4afe4716c0bdaa6fe7c7"
    encryptedData = data['platUserInfoMap']['encryptedData']
    iv = data['platUserInfoMap']['iv']
    req_params = {
        'appid': appID,
        'secret': appSecret,
        'js_code': code,
        'grant_type': 'authorization_code'
    }
    wx_login_api = 'https://api.weixin.qq.com/sns/jscode2session'
    response_data = requests.get(wx_login_api, params=req_params)  # 向API发起GET请求
    resData = response_data.json()
    openid = resData['openid']  # 得到用户关于当前小程序的OpenID
    session_key = resData['session_key']  # 得到用户关于当前小程序的会话密钥session_key

    pc = WXBizDataCrypt(appID, session_key)  # 对用户信息进行解密
    userinfo = pc.decrypt(encryptedData, iv)  # 获得用户信息

    user_info = User.query.filter_by(openid=openid).first()

    if not user_info:
        return json.dumps({"msg": "请注册", "res": "1", "openid": openid, "code": 400}, indent=4, sort_keys=True,
                          default=str,
                          ensure_ascii=False)

    if user_info.status != 1:
        return json.dumps({"msg": "锁定了"}, indent=4, sort_keys=True, default=str, ensure_ascii=False)

    name = user_info.nickname
    uid = user_info.id
    department = user_info.department
    company = user_info.company
    city = user_info.city
    status = user_info.status
    openid = user_info.openid
    role = user_info.role
    role = role.split(',')

    a = Weight.query.filter_by(city=city, type="用户应用").all()
    rtsu = []
    for item in a:
        temp = dict(name=item.name, image=item.image, fun=item.fun)
        rtsu.append(temp)
    rtsa = []
    for item1 in role:
        b = Weight.query.filter_by(role=item1, city=city, type="管理员应用").all()
        for item in b:
            temp = dict(name=item.name, image=item.image, fun=item.fun)
            rtsa.append(temp)

    return json.dumps(
        {"code": 200, "msg": "登录成功", "name": name, "uid": uid, "company": company, "department": department,
         "city": city, "status": status, "openid": openid, "weightu": rtsu, "weighta": rtsa},
        indent=4,
        sort_keys=True,
        default=str,
        ensure_ascii=False)


@member_page.route('/wxreg', methods=['GET', 'POST'])
def member_wxreg():
    req = request.values
    nickname = req['name'] if "name" in req else ""
    phone = req['phone'] if "phone" in req else ""
    department = req['department'] if "department" in req else ""
    company = req['company'] if "company" in req else ""
    city = req['city'] if "city" in req else ""
    openid = req['openid'] if "openid" in req else ""
    code = req['code'] if "code" in req else ""

    # 注册码
    regcode = "2777"

    user_info = User.query.filter_by(openid=openid).first()

    if user_info:
        return ops_renderErrJSON(msg="已注册成功，请返回登陆")

    if len(company) < 1 or company == "请选择":
        return ops_renderErrJSON(msg="请选择公司名称")

    if len(department) < 1 or department == "请选择":
        return ops_renderErrJSON(msg="请选择部门")

    if len(city) < 1 or city == "请选择":
        return ops_renderErrJSON(msg="请选择城市")

    if len(nickname) < 1:
        return ops_renderErrJSON(msg="请输入姓名")

    if len(phone) < 1:
        return ops_renderErrJSON(msg="请输入手机号")

    if code != regcode:
        return ops_renderErrJSON(msg="注册码错误，请联系对接您的公司招聘人员或公司IT")



    else:
        user_info = User()
        user_info.nickname = nickname
        user_info.phone = phone
        user_info.department = department
        user_info.company = company
        user_info.openid = openid
        user_info.city = city
        user_info.status = 1
        user_info.role = "用户"
        user_info.created_time = user_info.updated_time = getCurrentTime()
        db.session.add(user_info)
        db.session.commit()

        return json.dumps({"code": 200, "msg": "注册成功", }, indent=4,
                          sort_keys=True, default=str,
                          ensure_ascii=False)


@member_page.route("/reg", methods=["GET", "POST"])
def reg():
    if request.method == "GET":
        return ops_render("member/reg.html")

    req = request.values
    nickname = req['nickname'] if "nickname" in req else ""
    login_name = req['login_name'] if "login_name" in req else ""
    login_pwd = req['login_pwd'] if "login_pwd" in req else ""
    login_pwd2 = req['login_pwd2'] if "login_pwd2" in req else ""
    company = req['company'] if 'company' in req else ''
    city = req['city'] if 'city' in req else ''
    sn = req['sn'] if "sn" in req else ""

    if login_name is None or len(login_name) < 1:
        return ops_renderErrJSON(msg="请输入正确的登录用户名")

    if login_pwd is None or len(login_pwd) < 6:
        return ops_renderErrJSON(msg="请输入正确的登录密码，并且不能小于6个字符")

    if login_pwd != login_pwd2:
        return ops_renderErrJSON(msg="请输入正确的确认登录密码")

    if sn != "2777":
        return ops_renderErrJSON(msg="请输入正确的确认注册码")

    user_info = User.query.filter_by(login_name=login_name).first()
    if user_info:
        return ops_renderErrJSON(msg="登录用户名已被注册，请换一个")

    model_user = User.query.filter_by(nickname=nickname).first()
    if model_user:
        model_user.login_name = login_name
        model_user.nickname = nickname if nickname is not None else login_name
        model_user.login_salt = UserService.geneSalt(8)
        model_user.login_pwd = UserService.genePwd(login_pwd, model_user.login_salt)
        model_user.created_time = model_user.updated_time = getCurrentTime()
        db.session.add(model_user)
        db.session.commit()
        return ops_renderJSON(msg="注册成功~~")

    else:
        model_user = User()
        model_user.login_name = login_name
        model_user.nickname = nickname if nickname is not None else login_name
        model_user.login_salt = UserService.geneSalt(8)
        model_user.login_pwd = UserService.genePwd(login_pwd, model_user.login_salt)
        model_user.created_time = model_user.updated_time = getCurrentTime()
        model_user.company = company
        model_user.city = city
        model_user.department = "人事行政部"
        db.session.add(model_user)
        db.session.commit()

        return ops_renderJSON(msg="注册成功~~")
        # return ops_renderErrJSON(msg="找不到该用户")

    # model_user = User()


@member_page.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return ops_render("member/login.html")

    req = request.values
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''

    if login_name is None or len(login_name) < 1:
        return ops_renderErrJSON("请输入正确的登录用户名")

    if login_pwd is None or len(login_pwd) < 6:
        return ops_renderErrJSON("请输入正确的登录密码")
    user_info = User.query.filter_by(login_name=login_name).first()
    if not user_info:
        return ops_renderErrJSON("请输入正确的登录用户名和密码 -1")

    if user_info.login_pwd != UserService.genePwd(login_pwd, user_info.login_salt):
        return ops_renderErrJSON("请输入正确的登录用户名和密码 -2 ")

    if user_info.status != 1:
        return ops_renderErrJSON("账号被禁用，请联系管理员处理")

    # session['uid'] = user_info.id
    response = make_response(ops_renderJSON(msg="登录成功"))
    response.set_cookie(app.config['AUTH_COOKIE_NAME'],
                        "%s#%s" % (UserService.geneAuthCode(user_info), user_info.id), 60 * 60 * 24 * 120)
    return response


@member_page.route("/logout")
def logOut():
    response = make_response(redirect(UrlManager.buildUrl("/")))
    response.delete_cookie(app.config['AUTH_COOKIE_NAME'])
    return response


def pagessearch(member, type, content):
    req = request.values
    content = content
    type = type
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': member.count(),
        "page_size": 14,
        'page': page,
        'url': "/member/search?type=" + type + "&content=" + content,
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    member = member[offset:limit]

    return pages, member


def pagesadmin(member):
    req = request.values
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': member.count(),
        "page_size": 14,
        'page': page,
        'url': "/member/admin?",
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    member = member[offset:limit]

    return pages, member


def pagesupadte(member):
    req = request.values
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': member.count(),
        "page_size": 1,
        'page': page,
        'url': "/member/admin?",
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    member = member[offset:limit]

    return pages, member


@member_page.route('/admin', methods=['GET', 'POST'])
def memberadmin():
    city = request.args.get('city')
    if city == "太原":
        member = User.query.order_by(User.created_time.desc()).limit(14)
    else:
        member = User.query.filter_by(city=city).order_by(User.created_time.desc()).limit(14)

    company = Department.query.with_entities(Department.company).distinct().all()
    department = Department.query.with_entities(Department.department).distinct().all()
    city = City.query.with_entities(City.city).distinct().all()

    pages, member = pagesadmin(member)

    return ops_render("/admin/memberadmin.html",
                      {"member": member, "pages": pages, "company": company, "department": department, "city": city})

@member_page.route('/admin2', methods=['GET', 'POST'])
def memberadmin2():
    # city = request.args.get('city')
    # if city == "太原":
    #     member = User.query.order_by(User.created_time.desc()).limit(14)
    # else:
    #     member = User.query.filter_by(city=city).order_by(User.created_time.desc()).limit(14)
    #
    # company = Department.query.with_entities(Department.company).distinct().all()
    # department = Department.query.with_entities(Department.department).distinct().all()
    # city = City.query.with_entities(City.city).distinct().all()
    #
    # pages, member = pagesadmin(member)

    return ops_render("/member/memberlist.html")


@member_page.route('/search', methods=['GET', 'POST'])
def membersearch():
    content = request.args.get('content')
    type = request.args.get('type')
    company = Department.query.with_entities(Department.company).distinct().all()
    department = Department.query.with_entities(Department.department).distinct().all()
    city = City.query.with_entities(City.city).distinct().all()
    if type == "姓名":
        member = User.query.filter_by(nickname=content)
        pages, member = pagessearch(member, type, content)
        return ops_render("/admin/memberadmin.html",
                          {"member": member, "pages": pages, "type": type, "content": content, "company": company, "department": department, "city": city})
    if type == "公司":
        member = User.query.filter_by(company=content)
        pages, member = pagessearch(member, type, content)
        return ops_render("/admin/memberadmin.html",
                          {"member": member, "pages": pages, "type": type, "content": content, "company": company, "department": department, "city": city})
    if type == "部门":
        member = User.query.filter_by(department=content)
        pages, member = pagessearch(member, type, content)
        return ops_render("/admin/memberadmin.html",
                          {"member": member, "pages": pages, "type": type, "content": content, "company": company, "department": department, "city": city})
    if type == "城市":
        member = User.query.filter_by(city=content)
        pages, member = pagessearch(member, type, content)
        return ops_render("/admin/memberadmin.html",
                          {"member": member, "pages": pages, "type": type, "content": content, "company": company, "department": department, "city": city})


@member_page.route('/adminupdate', methods=['GET', 'POST'])
def adminupdate():
    req = request.values
    company = req['company'] if "company" in req else ""
    id = req['id'] if "id" in req else ""
    name = req['name'] if "name" in req else ""
    department = req['department'] if "department" in req else ""
    city = req['city'] if "city" in req else ""
    phone = req['phone'] if "phone" in req else ""
    role = req['role'] if "role" in req else ""

    b = User.query.filter_by(id=id).first()

    b.nickname = name
    b.company = company
    b.department = department
    b.city = city
    b.phone = phone
    b.role = role

    db.session.commit()

    return ops_render("/admin/memberadmin.html")
